from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth.hashers import make_password
import json
from .models import UserModel


class LoginViewTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.login_url = reverse('users-login')  # 使用视图的URL名称

        # 创建测试用户并使用哈希密码（更安全）
        self.user = UserModel.objects.create(
            username="testuser",
            password='111111',  # 使用哈希密码
            email="test@example.com",
            phone="13800138000"
        )

    def test_successful_login(self):
        """测试使用用户名成功登录"""
        response = self.client.post(
            self.login_url,
            data=json.dumps({'account': 'testuser', 'password': '111111'}),
            content_type='application/json'
        )
        data = response.json()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['code'], 200)
        self.assertEqual(data['msg'], "登录成功")
        self.assertIn('token', data['data'])
        self.assertEqual(data['data']['username'], "testuser")

    def test_login_with_email(self):
        """测试使用邮箱成功登录"""
        response = self.client.post(
            self.login_url,
            data=json.dumps({'account': 'test@example.com', 'password': '111111'}),
            content_type='application/json'
        )
        data = response.json()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['code'], 200)
        self.assertEqual(data['data']['username'], "testuser")

    def test_login_with_phone(self):
        """测试使用手机号成功登录"""
        response = self.client.post(
            self.login_url,
            data=json.dumps({'account': '13800138000', 'password': '111111'}),
            content_type='application/json'
        )
        data = response.json()  # 将 JSON 响应体解析为 Python 字典
        # 断言验证
        self.assertEqual(response.status_code, 200)  # 验证 HTTP 状态码为 200
        self.assertEqual(data['code'], 200)  # 验证业务状态码为 200
        self.assertEqual(data['data']['username'], "testuser")  # 验证返回的用户名

    def test_login_user_not_found(self):
        """测试用户不存在的情况"""
        response = self.client.post(
            self.login_url,
            data=json.dumps({'account': 'nonexistent', 'password': '111111'}),
            content_type='application/json'
        )
        data = response.json()
        self.assertEqual(response.status_code, 400)
        self.assertEqual(data['code'], 400)
        self.assertEqual(data['msg'], "用户不存在")

    def test_login_wrong_password(self):
        """测试密码错误的情况"""
        response = self.client.post(
            self.login_url,
            data=json.dumps({'account': 'testuser', 'password': 'wrong'}),
            content_type='application/json'
        )
        data = response.json()
        self.assertEqual(response.status_code, 400)
        self.assertEqual(data['code'], 400)
        self.assertEqual(data['msg'], "密码错误")

